package com.tanhua.sso.service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.tanhua.sso.config.AliyunSMSConfig;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Date;
import java.util.Map;

@Slf4j
@Service
public class SmsService {

    @Autowired
    private AliyunSMSConfig aliyunSMSConfig;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发送短信验证码
     *
     * @param mobile
     * @return
     */
    public String sendSms(String mobile) {


//        DefaultProfile profile = DefaultProfile.getProfile(aliyunSMSConfig.getRegionId(),
//                aliyunSMSConfig.getAccessKeyId(), aliyunSMSConfig.getAccessKeySecret());
//        IAcsClient client = new DefaultAcsClient(profile);

        String code = RandomUtils.nextInt(100000, 999999) + "";
//        code="123456";

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                "LTAI4G86uuTwvEzTfTNwCBWU", "NQFc7EIzt96hduVQPiVdMMmbTtNVGw");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", mobile); //目标手机号
        request.putQueryParameter("SignName", "黑马旅游网验证码验证"); //签名名称
        request.putQueryParameter("TemplateCode", "SMS_204107168"); //短信模板code
        request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");//模板中变量替换
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            if(StringUtils.contains(data,"Message\":\"OK")) {
                return code;
            }
            //{"Message":"OK","RequestId":"EC2D4C9A-0EAC-4213-BE45-CE6176E1DF23","BizId":"110903802851113360^0","Code":"OK"}
            log.info("短信验证码发送失败~ data:"+data);
        } catch (Exception e) {
            log.error("发送短息验证码失败~mobile= "+mobile,e);
//            e.printStackTrace();
        }
        //用户登录名称 tanhua@1836512316159028.onaliyun.com
        //AccessKey ID LTAI4G1S14A2oFKe7URPpPQB
        //AccessKey Secret 8Tz84pEhGP6s9xIUkEBUCPikLLJ5ZS
            return null;
    }

    /**
     *  发送短信验证码
     *  发送短信验证码后，需要将验证码保存到redis中
     * @param phoneNumber
     * @return
     */
    public ErrorResult sendCheckCode(String phoneNumber) {
       String redisKey="CHECK_CODE_"+phoneNumber;
        //判断redis中的是否失效
        if(this.redisTemplate.hasKey(redisKey)){
            String msg="上一次的验证码还未失效";
            return ErrorResult.builder().errCode("000001").errMessage(msg).build();
        }

        //是否写死
        if (true){
            String code1="123456";
//        this.redisTemplate.opsForValue().set(redisKey,code, Duration.minutes());
            this.redisTemplate.opsForValue().set(redisKey,code1, Duration.ofMinutes(10));
            return null;
        }


        //发送验证码
        String code = this.sendSms(phoneNumber);


        if(StringUtils.isEmpty(code)){
            String msg="发送短信验证码失败";
            return ErrorResult.builder().errCode("000000").errMessage(msg).build();
        }

        //是否写死
//        code="123456";
//        this.redisTemplate.opsForValue().set(redisKey,code, Duration.minutes());
        this.redisTemplate.opsForValue().set(redisKey,code, Duration.ofMinutes(10));
        return null;
    }
}
